package database.didactic;

import database.ConnectionFactory;
import database.util.Queries;
import model.didactic.Activity;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * User: kosta
 * Date: 1/1/13
 * Time: 7:21 PM
 * To change this template use File | Settings | File Templates.
 */
public class ActivityDao {

    public static ArrayList<Activity> getActivities(){
        ArrayList<Activity> result = new ArrayList<Activity>();
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            connection = ConnectionFactory.getConnection();
            statement = connection.createStatement();
            resultSet = statement.executeQuery(Queries.ACTIVITIES_SELECT_QUERY);
            result = toActivities(resultSet);
        } catch (SQLException e) {
            System.err.println("ActivityDao.getActivities Error db");
            e.printStackTrace();
        } finally {
            try{
                if (resultSet!=null) resultSet.close();
                if (statement!=null) statement.close();
                if (connection!=null) connection.close();
            } catch (SQLException e) {
                System.err.println("ActivityDao.getActivities finally block error");
                e.printStackTrace();
            }
        }
        return result;
    }






    private static ArrayList<Activity> toActivities(ResultSet rs){
        ArrayList<Activity> result = new ArrayList<Activity>();
        try {
            while (rs.next()) {
                Activity activity = toActivity(rs);
                result.add(activity);
            }
        } catch (SQLException e) {
            System.err.println("toActivities ResultSetError");
            e.printStackTrace();
        } catch (Exception e) {
            System.err.println("toActivities unknown ResultSetError");
            e.printStackTrace();
        }
        return result;
    }

    private static Activity toActivity(ResultSet rs) throws SQLException {
        if (rs == null || rs.isClosed()){
            throw new SQLException("ResultSet Closed !!!");
        }
        Activity activity;
        activity=new Activity();
        activity.setId(rs.getInt(1));
        activity.setActivityType(rs.getInt(2));
        activity.setActivityName(rs.getString(3));
        activity.setDescription(rs.getString(4));
        activity.setValidFromDate(new Date(rs.getTimestamp(5).getTime()));
        activity.setExpireDate(new Date(rs.getTimestamp(6).getTime()));
        activity.setEnabled(rs.getInt(7)>0);

        return activity;
    }
}
